
package com.yadong.smarthome2.ui;

import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.yadong.smarthome2.R;
import com.yadong.smarthome2.control.ControlCenterService;
import com.yadong.smarthome2.control.ControlRules;
import com.yadong.smarthome2.control.ControlRules.RuleBuilder;
import com.yadong.smarthome2.device.Device;
import com.yadong.smarthome2.device.DeviceManagerService;
import com.yadong.smarthome2.device.DeviceManagerService.MyBinder;
import com.yadong.smarthome2.protocol2.RequestProtocol.Parameter;
import com.yadong.smarthome2.protocol2.ResultProtocol.DeviceInfo.Status;
import com.yadong.smarthome2.protocol2.ResultProtocol.Function;

public class RuleAddActivity extends Activity {
    private enum Setup {
        CHOOSEDEVICE, CHOOSESTATUS, SETLIMIT, CHOOSETARGETDEVICE, CHOOSEACTION, SETPARAMETER
    }

    private DeviceManagerService mDeviceManagerService;
    private ControlCenterService mControlCenterService;

    private ListView mListView;
    private Button mButton;
    private Setup mSetup = Setup.CHOOSEDEVICE;
    private RuleBuilder mRuleBuilder;
    private DeviceListAdapter mDeviceListAdapter;
    private StatusListAdapter mStatusListAdapter;
    private FunctionListAdapter mFunctionListAdapter;
    private Dialog mShowingDialog;
    private Function mChoosedFunction;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rule_add_layout);
        mRuleBuilder = new RuleBuilder();
        mListView = (ListView) findViewById(R.id.list);
        mButton = (Button) findViewById(R.id.button);

        Intent deviceManagerIntent = new Intent(RuleAddActivity.this,
                DeviceManagerService.class);
        bindService(deviceManagerIntent, mServiceConnection, BIND_AUTO_CREATE);
        Intent controlCenterIntent = new Intent(RuleAddActivity.this,
                ControlCenterService.class);
        bindService(controlCenterIntent, mControlCenterConnection, BIND_AUTO_CREATE);
        mDeviceListAdapter = new DeviceListAdapter(this);
        mStatusListAdapter = new StatusListAdapter(this);
        mFunctionListAdapter = new FunctionListAdapter(this);
        mListView.setOnItemClickListener(mOnItemClickListener);
        mButton.setOnClickListener(mButtonClickListener);
    }

    private OnClickListener mButtonClickListener = new OnClickListener() {
        @Override
        public void onClick(View view) {
            moveToNextSetup();
        }
    };

    private OnItemClickListener mOnItemClickListener = new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView,
                View view, int position, long id) {
            switch (mSetup) {
                case CHOOSEDEVICE: {
                    Device device = (Device) mDeviceListAdapter.getItem(position);
                    mRuleBuilder.setmDevice(device);
                    moveToNextSetup();
                    break;
                }
                case CHOOSESTATUS:
                    Status status = (Status) mStatusListAdapter.getItem(position);
                    mRuleBuilder.addStatus(status);
                    break;
                case CHOOSETARGETDEVICE: {
                    Device device = (Device) mDeviceListAdapter.getItem(position);
                    mRuleBuilder.setmTargetDevice(device);
                    moveToNextSetup();
                    break;
                }
                case CHOOSEACTION: {
                    Function function = (Function) mFunctionListAdapter.getItem(position);
                    mRuleBuilder.setmDoFunction(function.getCode());
                    mChoosedFunction = function;
                    moveToNextSetup();
                    break;
                }
                default:
                    break;
            }
        }
    };

    private void moveToPreviousSetup() {
        if (mSetup != Setup.CHOOSEDEVICE) {
            mSetup = Setup.values()[mSetup.ordinal() - 1];
            onSetupChanged();
        } else {
            finish();
        }
    }

    @Override
    public void onBackPressed() {
        moveToPreviousSetup();
    }

    private void moveToNextSetup() {
        if (mSetup != Setup.SETPARAMETER) {
            mSetup = Setup.values()[mSetup.ordinal() + 1];
        } else {
            mSetup = Setup.CHOOSEDEVICE;
        }
        onSetupChanged();
    }

    private void onSetupChanged() {
        switch (mSetup) {
            case CHOOSEDEVICE:
                mDeviceListAdapter.setDevices(mDeviceManagerService.getFindedDevice());
                mListView.setAdapter(mDeviceListAdapter);
                mListView.postInvalidate();
                mButton.setText("选择监控设备");
                mButton.setEnabled(false);
                break;
            case CHOOSESTATUS:
                mStatusListAdapter.setStatus(mRuleBuilder.getmDevice().getStatus());
                mListView.setAdapter(mStatusListAdapter);
                mListView.postInvalidate();
                mButton.setText("选择触发状态");
                mButton.setEnabled(true);
                break;
            case SETLIMIT:
                final InputStatusDialogBuilder dialogBuilder =
                        new InputStatusDialogBuilder(this);
                mShowingDialog = dialogBuilder
                        .createInputDailog(mRuleBuilder.getmStatuses());
                mShowingDialog.setCancelable(false);
                mShowingDialog.show();
                mShowingDialog.setOnDismissListener(new OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        List<Status> statuses = dialogBuilder.getAllParameters();
                        if (statuses != null && statuses.size() > 0) {
                            mRuleBuilder.setmStatus(dialogBuilder.getAllParameters());
                            mRuleBuilder.setmJustRight(
                                    dialogBuilder.getAllParameters().get(0).getValue());
                            moveToNextSetup();
                        } else {
                            moveToPreviousSetup();
                        }
                    }
                });
                break;
            case CHOOSETARGETDEVICE:
                mDeviceListAdapter.setDevices(mDeviceManagerService.getFindedDevice());
                mListView.setAdapter(mDeviceListAdapter);
                mListView.postInvalidate();
                mButton.setText("选择目标设备");
                mButton.setEnabled(false);
                break;
            case CHOOSEACTION:
                mFunctionListAdapter.setFunctions(
                        mRuleBuilder.getmTargetDevice().getFunctions());
                mListView.setAdapter(mFunctionListAdapter);
                mListView.postInvalidate();
                mButton.setText("选择执行方法");
                mButton.setEnabled(false);
                break;
            case SETPARAMETER:
                final InputParameterDialogBuilder parameterDialogBuilder =
                        new InputParameterDialogBuilder(this);
                mShowingDialog = parameterDialogBuilder
                        .createInputDailog(mChoosedFunction.getArgumentsList());
                mShowingDialog.setCancelable(false);
                mShowingDialog.setOnDismissListener(new OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface arg0) {
                        List<Parameter> parameters = parameterDialogBuilder.getAllParameters();
                        if (parameters != null && parameters.size() > 0) {
                            mRuleBuilder.setmParameters(
                                    parameterDialogBuilder.getAllParameters());
                            onBuildRuleEnd();
                        }
                    }
                });
                mShowingDialog.show();
                break;
            default:
                break;
        }
    }

    private void onBuildRuleEnd() {
        ControlRules controlRule = mRuleBuilder.build();
        if (mControlCenterService.addRule(controlRule)) {
            Toast.makeText(this, "add rule success!!", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mShowingDialog != null && mShowingDialog.isShowing()) {
            mShowingDialog.dismiss();
        }
        unbindService(mServiceConnection);
        unbindService(mControlCenterConnection);
    }

    private ServiceConnection mControlCenterConnection = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            mControlCenterService = null;
        }

        @Override
        public void onServiceConnected(ComponentName arg0, IBinder binder) {
            mControlCenterService = ((ControlCenterService.MyBinder) binder).getService();
        }
    };

    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder binder) {
                mDeviceManagerService = ((MyBinder) binder).getService();
                onSetupChanged();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
                mDeviceManagerService = null;
        }
    };

}
